const Fabric_Client = require('fabric-client');
const Fabric_CA_Client = require('fabric-ca-client');
const path = require('path');
const fabric_client = new Fabric_Client();


let username = 'afc_data';
let password = 'password';
let ca_address = "http://192.168.0.136:7054";
let store_path = path.resolve(__dirname, './hfc-key-store-org1');

Fabric_Client.newDefaultKeyValueStore({
    path: store_path
}).then((state_store) => {

    fabric_client.setStateStore(state_store);
    let crypto_suite = Fabric_Client.newCryptoSuite();
    let crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
    crypto_suite.setCryptoKeyStore(crypto_store);
    fabric_client.setCryptoSuite(crypto_suite);

    let fabric_ca_client = new Fabric_CA_Client(ca_address, null, '', crypto_suite);
    return fabric_ca_client.enroll({enrollmentID: username, enrollmentSecret: password});

}).then((enrollment) => {
    console.log(`Successfully enrolled member user ${username}`);
    return fabric_client.createUser({
        username: username,
        mspid: 'Org1MSP',
        cryptoContent: {privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate}
    });
}).then((user) => {
    return fabric_client.setUserContext(user);

}).then(() => {
    console.log(`${username} was successfully registered and enrolled and is ready to intreact with the fabric network`);
    return {
        "error_code": 0,
        "data": "login success"
    }

}).catch((err) => {
    console.error('Failed to login: ' + err);
    if (err.toString().indexOf('Authorization') > -1) {
        console.error('Authorization failures may be caused by having admin credentials from a previous CA instance.\n' +
            'Try again after deleting the contents of the store directory ' + store_path);
    }
    return {
        "error_code": 20000,
        "error_msg": "login fail"
    }
});
